{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 神经网络\n",
    "\n",
    "神经网络主要通过调用 `torch.nn` 包来构建，并采用`nn.Module`来构建网络层，调用其方法 `forward(input)` 得到输出 `output` "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 网络定义"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Net(\n",
      "  (conv1): Conv2d(1, 6, kernel_size=(5, 5), stride=(1, 1))\n",
      "  (conv2): Conv2d(6, 16, kernel_size=(5, 5), stride=(1, 1))\n",
      "  (fc1): Linear(in_features=400, out_features=120, bias=True)\n",
      "  (fc2): Linear(in_features=120, out_features=84, bias=True)\n",
      "  (fc3): Linear(in_features=84, out_features=10, bias=True)\n",
      ")\n"
     ]
    }
   ],
   "source": [
    "import torch\n",
    "import torch.nn as nn\n",
    "import torch.nn.functional as F\n",
    "\n",
    "\n",
    "class Net(nn.Module):\n",
    "    def __init__(self):\n",
    "        super(Net,self).__init__()\n",
    "        self.conv1=nn.Conv2d(1,6,5)\n",
    "        self.conv2=nn.Conv2d(6,16,5)\n",
    "        \n",
    "        self.fc1=nn.Linear(16*5*5,120)\n",
    "        self.fc2=nn.Linear(120,84)\n",
    "        self.fc3=nn.Linear(84,10)\n",
    "        \n",
    "    def forward(self,x):\n",
    "        x=F.max_pool2d(F.relu(self.conv1(x)),(2,2))\n",
    "        \n",
    "        x=F.max_pool2d(F.relu(self.conv2(x)),2)\n",
    "        x=x.view(-1,self.num_flat_features(x))\n",
    "        x=F.relu(self.fc1(x))\n",
    "        x=F.relu(self.fc2(x))\n",
    "        x=self.fc3(x)\n",
    "        return x\n",
    "    \n",
    "    def num_flat_features(self,x):\n",
    "        size=x.size()[1:]\n",
    "        num_features=1\n",
    "        for s in size:\n",
    "            num_features*=s\n",
    "        return num_features\n",
    "    \n",
    "net=Net()\n",
    "print(net)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 定义参数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "参数数量： 10\n",
      "第一个参数大小： torch.Size([6, 1, 5, 5])\n"
     ]
    }
   ],
   "source": [
    "params=list(net.parameters())\n",
    "print('参数数量：',len(params))\n",
    "\n",
    "print('第一个参数大小：',params[0].size())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 随机定义一个变量输入网络"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "tensor([[-0.0066,  0.0294, -0.0209,  0.0843, -0.0672, -0.0614, -0.0017, -0.0685,\n",
      "         -0.0779,  0.0423]], grad_fn=<AddmmBackward0>)\n"
     ]
    }
   ],
   "source": [
    "input=torch.randn(1,1,32,32)\n",
    "out =net(input)\n",
    "print(out)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "####  清空所有参数的梯度缓存，然后计算随机梯度进行反向传播"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [],
   "source": [
    "net.zero_grad()\n",
    "out.backward(torch.randn(1,10))\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 损失函数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "tensor(0.9843, grad_fn=<MseLossBackward0>)\n",
      "<MseLossBackward0 object at 0x000001767E70FD30>\n",
      "<AddmmBackward0 object at 0x00000176023F2920>\n",
      "<AccumulateGrad object at 0x000001767E70FD30>\n"
     ]
    }
   ],
   "source": [
    "output=net(input)\n",
    "target=torch.randn(10)\n",
    "\n",
    "target=target.view(1,-1)\n",
    "criterion=nn.MSELoss()\n",
    "\n",
    "loss=criterion(output,target)\n",
    "print(loss)\n",
    "\n",
    "print(loss.grad_fn)\n",
    "\n",
    "\n",
    "print(loss.grad_fn.next_functions[0][0])\n",
    "\n",
    "print(loss.grad_fn.next_functions[0][0].next_functions[0][0])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 反向传播"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "conv1.bias.grad before backward\n",
      "None\n",
      "conv1.bias.grad after backward\n",
      "tensor([-0.0161,  0.0209, -0.0129,  0.0148, -0.0018,  0.0036])\n"
     ]
    }
   ],
   "source": [
    "# 清空所有参数的梯度缓存\n",
    "net.zero_grad()\n",
    "print('conv1.bias.grad before backward')\n",
    "print(net.conv1.bias.grad)\n",
    "\n",
    "loss.backward()\n",
    "\n",
    "print('conv1.bias.grad after backward')\n",
    "print(net.conv1.bias.grad)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 更新权重"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [],
   "source": [
    "learning_rate=0.01\n",
    "for f in net.parameters():\n",
    "    f.data.sub_(f.grad.data * learning_rate)\n",
    "    \n",
    "\n",
    "import torch.optim as optim\n",
    "\n",
    "optimizer=optim.SGD(net.parameters(),lr=0.01)\n",
    "\n",
    "optimizer.zero_grad()\n",
    "output=net(input)\n",
    "loss=criterion(output,target)\n",
    "loss.backward()\n",
    "\n",
    "optimizer.step()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
